import { pathOr } from 'ramda';
import errorCodesBuilder from '../../../helpers/errorCodesBuilder';
import { LIMITERS } from './../constants.js';

const errorCodes = errorCodesBuilder('检查余额异常');

export default async function ensureBalance({ uid, ops }) {
	const {
		log,
		app: {
			model: { Balance },
		},
	} = this;

	let record;
	try {
		record = await Balance.findOne({ uid });
	} catch (err) {
		const error = errorCodes['[0F][检查余额]查询余额Mongo记录失败'].from(err);
		log.error({ error, uid, ops }, error.rawMessage);
		throw error;
	}
	if (!record) {
		const error = errorCodes['[0F][检查余额]没有查询到对于余额Mongo记录'];
		log.error({ error, uid }, error.rawMessage);
		throw error;
	}

	if (!record.planId) {
		const error = errorCodes['[0F][检查余额]未购买套餐'];
		log.error({ error, uid }, error.rawMessage);
		throw error;
	}

	if (record.planExpireTime < Date.now()) {
		const error = errorCodes['[0F][检查余额]套餐已过期'];
		log.error({ error, uid }, error.rawMessage);
		throw error;
	}

	ops
		.filter(x => x.value !== 0)
		.forEach(({ key, value }) => {
			const limit = pathOr({ total: 0, used: 0 }, ['balance', key], record);
			limit.used -= value;
			if (limit.used > limit.total) {
				const error = errorCodes['[0F][检查余额]当前余额不足以执行该操作'];
				error.message = `[${error.code}]${LIMITERS[key].label}已达到套餐限制，无法执行该操作`;
				log.error({ error, uid, key, value }, error.rawMessage);
				throw error;
			}
		});
}
